#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QFileInfoList>
#include <QStack>
#include <QImage>
#include <QFileDialog>
#include <QDebug>

#define MIN_WINDOW_WIDTH 700
#define MIN_WINDOW_HEIGHT 1100

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("图像预览");
    setFixedSize(MIN_WINDOW_WIDTH,MIN_WINDOW_HEIGHT);

    ui->WindowWidthLineEdit->setText(QString::number(MIN_WINDOW_WIDTH));
    ui->WindowHeightLineEdit->setText(QString::number(MIN_WINDOW_HEIGHT));

    _image_thread = new ImageLoadThread;
    _move_thread = new QThread;

    // 图像发送到ui
    connect(_image_thread,&ImageLoadThread::sig_loadImage,
            this,&MainWindow::slot_updateImagePreView);

    // 停止按键点击
    connect(ui->stopBtn,&QPushButton::clicked,_image_thread,&ImageLoadThread::stopWork);
    // 窗体销毁
    connect(this,&MainWindow::destroyed,this,&MainWindow::slot_destoryedThread);
    connect(_move_thread,&QThread::started,_image_thread,&ImageLoadThread::initTimer);

    // 移动到线程中
    _image_thread->moveToThread(_move_thread);
    _is_start = false;
    // 线程启动
    _move_thread->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slot_updateImagePreView(const QImage &image)
{
    if(image.isNull()){

        return;
    }
    QPixmap pixmap = QPixmap::fromImage(image);
    pixmap = pixmap.scaled(ui->ImagePreLabel->width(),ui->ImagePreLabel->height(),
                  Qt::KeepAspectRatio,Qt::SmoothTransformation);

    // 给标签添加图片
    ui->ImagePreLabel->setPixmap(pixmap);

}

void MainWindow::on_startBtn_clicked()
{
    // 线程一直跑呗，我控制定时器显示和不显示
    QString folderPath = ui->ImageLineEdit->text();
    if(folderPath.isEmpty()){
         _is_start = false;
        return;
    }

    QString time = ui->comboBox->currentText();

    QMetaObject::invokeMethod(_image_thread,"startWork",
                              Qt::QueuedConnection,
                              Q_ARG(float,time.toFloat()),
                              Q_ARG(QString,folderPath));
    ui->startBtn->setEnabled(false);
    _is_start = true;
}

void MainWindow::on_stopBtn_clicked()
{
    if(!_is_start){
       return;
    }

    _is_start = false;
    ui->startBtn->setEnabled(true);

    QMetaObject::invokeMethod(_image_thread,"stopWork",Qt::QueuedConnection);
}

void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    Q_UNUSED(arg1);
    QString time = ui->comboBox->currentText();

    QMetaObject::invokeMethod(_image_thread,"setTimerInterval",Qt::QueuedConnection
                              ,Q_ARG(float,time.toFloat()));
}

void MainWindow::on_folderBtn_clicked()
{
    QString folderPath = QFileDialog::getExistingDirectory(this,tr("图像预览"),"E:/"
                ,QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if(!folderPath.isEmpty()){
        ui->ImageLineEdit->setText(folderPath);
    }
}

void MainWindow::slot_destoryedThread()
{
    // 1. 先停止定时器（通过信号槽跨线程调用，确保在子线程中执行）
    if (_image_thread) {
        QMetaObject::invokeMethod(_image_thread, "stopWork", Qt::QueuedConnection);
    }

    // 2. 等待定时器停止完成（增加延迟确保操作生效）
    QThread::msleep(100);

    // 3. 退出线程并等待
    if (_move_thread && _move_thread->isRunning()) {
        _move_thread->quit();
        if (!_move_thread->wait(500)) {
            qWarning() << "线程退出超时，强制终止";
            _move_thread->terminate();
            _move_thread->wait();
        }
    }

    // 4. 释放资源（此时线程已退出，可安全删除）
    delete _image_thread;
    _image_thread = nullptr;
    delete _move_thread;
    _move_thread = nullptr;
}

void MainWindow::on_ConfirmBtn_clicked()
{
    int width = ui->WindowWidthLineEdit->text().toInt();
    int height = ui->WindowHeightLineEdit->text().toInt();

    width = qMax(width,MIN_WINDOW_WIDTH);
    height = qMax(height,MIN_WINDOW_HEIGHT);

    setFixedSize(width,height);
    adjustSize();

    if(!_is_start){
        // 将中间图像在进行缩放
        const QPixmap* pixmap = ui->ImagePreLabel->pixmap();
        if(pixmap == nullptr){
            return;
        }
        QPixmap copy = *pixmap;

        copy = copy.scaled(ui->ImagePreLabel->width(),
                               ui->ImagePreLabel->height(),
                               Qt::KeepAspectRatio,Qt::SmoothTransformation);
        ui->ImagePreLabel->setPixmap(copy);
    }
}
